// pages/index/index.js
const app = getApp();
const requestUtil = require('../../../utils/requestUtil');
const util = require('../../../utils/util');
const _DgData = require('../../../utils/data');
import WxParse from '../../../wxParse/wxParse';
import _ from '../../../utils/underscore';

Page({
  data: {
    // ------------------------多店版数据start----------------------------------
    //用来限制自定义上啦下拉操作间隔 防止过于频繁触发
    reachBottom_delayTime: 0,
    store_type: '',
    store_cate: '',
    single_store_info: [],
    page_index: 1,
    storeListArr: [],
    is_toLoad: false,
    param: {
      keyword: '',
      type: 0
    },
    is_show_getLocation: false,
    isTabFixed: false,//用来控制排序栏置顶
    sort_index:4,

    // -------------------------多店版数据end------------------------------------
    g_share_title: '',
    g_share_desc: '',
    is_show_load_bg: true,//控制整个界面显示，没有加载好则显示默认背景
    // -------------------------单店版数据start----------------------------------
    search_p: '搜索',
    source_data: {},
    goods_data_waimai: [],
    goods_data_diannei: [],
    store_data: false,
    tabTit: '',
    this_store_id: 0,
    //用来控制是立即购买 还是购物车选好了
    consume_type: '',
    //控制购物车显示
    cart_list_isshow: false,
    cart_list: [],
    store_yingye_status_text: '未营业',
    store_yingye_status_val: 2,
    store_button_status: true,
    //提交btn loading
    submitIsLoading: false,
    //显示规格
    guigeIsShow: false,
    //商品属性选择
    goods_attr_select: {},
    goods_specification: '',
    goods_a_info: {},

    //930改版
    store_data: false,
    this_store_id: 0,
    is_show_back_home: false
    // ------------------------单店版数据end------------------------------------
  },
  //---------------------单门店和多门店公用部分 start-------------------------------------
  onLoad: function (options) {
    //获取配置  单店或多店等
    this.tabOffsetTop = null;
    this.getStoreConfig();
    this.getShareData();
  },
  //下拉动作
  onPullDownRefresh: function () {
    var that = this;
    that.data.page_index = 1;
    that.getStoreConfig();
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1500);
  },
  //上拉
  onReachBottom: function () {
    var that = this;
    if (that.data.store_type == 2) {//多店
      if (that.data.page_index>1){
        that.getStoreList(that.data.page_index);
    }
     
    }
    else {
      // 单店

    }
  },
  //出现
  onShow: function () {
    var that = this;
    if (that.data.store_type == 1) {//单店
      that.setData({
        submitIsLoading: false
      });
      that.getStoreInfo();
    }
    else {
      //多店

    }
  },
  //获取分享信息
  getShareData: function () {
    var that = this;
    requestUtil.get(_DgData.duoguan_get_share_data_url, { mmodule: 'dg_store' }, (data) => {
      that.setData({
        g_share_title: data.title,
        g_share_desc: data.desc
      })
    });
  },
  //获取配置信息
  getStoreConfig: function () {
    var that = this;
    requestUtil.get(_DgData.duoguan_host_api_url + '/index.php?s=/addon/DgStore/Api/getStoreConfig.html', {}, (info) => {
      that.data.store_type = info.store_type;
      if (info.market_config && info.market_config.market_status==1){
      var is_show_market=1;
      }
      else
      {
        var is_show_market = 0;
      }
      that.setData({
        is_ruzhu: info.is_ruzhu,
        is_show_market:is_show_market
      });
      if (info.store_type == 1) {
        // 单门店
        that.data.this_store_id = info.store_id;
        that.setData({
          store_type: info.store_type,
        });
        that.getStoreInfo();
      }
      else if (info.store_type == 2) {
        //多门店
        that.setData({
          store_type: info.store_type,
        });
        var lat = wx.getStorageSync('LATITUD')
        var lng = wx.getStorageSync('LONGITUDE')
        var address = wx.getStorageSync('ADDRESS')
        if (lat && lng && address && lat != 'undefined' && lng != 'undefined') {
          that.setData({
            address: address,
          });
          that.getManyStoresSource();
        }
        else {
          that.setData({
            is_show_load_bg: false,
            is_show_getLocation: true,
          });
          that.getLocation();
        }

      }
    }, that, { isShowLoading:false});
  },
  //---------------------单门店和多门店公用部分 end-------------------------------------
  //------------------------------ 多门店首页 start-------------------------------------
//跳转市集
  jump_market(){
    wx.navigateTo({
      url: '../market-index/index'
    });
  },
  //门店排序 栏  控制顶部浮动
  onPageScroll(e) {
    if (this.tabOffsetTop !== null) {
        var distance = e.scrollTop - this.tabOffsetTop + 46;
        var isTabFixed = distance>=0?true:false;
        if (this.data.isTabFixed != isTabFixed){
          this.setData({ isTabFixed: isTabFixed });
        }

    }
  },
  /**
 * 更新tab距离顶部距离
 */
  updateTabOffsetTop() {
    const selectorQuery = wx.createSelectorQuery();
    selectorQuery.select('#store_list').boundingClientRect();
    selectorQuery.selectViewport().scrollOffset();
    selectorQuery.exec((res) => {
      if (this.tabOffsetTop == null) {
        this.tabOffsetTop = res[0].top
      }
    });
  },
  //排序
  sort_select:function(e){
    var that=this;
   var index=e.currentTarget.id;
    this.setData({
      sort_index: index,
    });
    that.data.page_index = 1;
    that.getStoreList();
   
  },

  //多店请求
  getManyStoresSource: function () {
    var that = this;
    //获取门店分类和广告图片
    requestUtil.get(_DgData.duoguan_host_api_url + "/index.php?s=/addon/DgStore/Api/getStoreCategoryAndAdvert.html", {}, (info) => {
      var categoryList = info.categoryList;
      var advertList = info.advert;
      var advertCount = advertList.length;
      var is_indicatorDots = false;
      is_indicatorDots = info.category_num < 10 ? false : true;

      this.setData({
        is_show_load_bg: false,
        store_category_list: info.categoryList,
        store_category_num: info.category_num,
        advertList: advertList,
        advertCount: advertCount,
        indicatorDots: is_indicatorDots
      });
      if (wx.createSelectorQuery) {
        setTimeout(this.updateTabOffsetTop, 500);
      }

    }, that, { isShowLoading: false });
    that.getStoreList();
  },
  //获取店铺列表
  getStoreList: function (page_index=1) {
    var that = this;
    var lat = wx.getStorageSync('LATITUD')
    var lng = wx.getStorageSync('LONGITUDE')
    var address = wx.getStorageSync('ADDRESS')
    if(!lat&&!lng&&that.data.sort_index==1){
      that.setData({
        is_show_load_bg: false,
        is_show_getLocation: true,
      });
      that.getLocation();
    }
    //获取门店列表
    requestUtil.get(_DgData.duoguan_host_api_url + '/index.php?s=/addon/DgStore/Api/getStoreList.html', { version: 2, page_index: page_index, ws_lat: lat, ws_lng: lng, store_cate: that.data.store_cate, keywords: that.data.param.keyword, sort_type: that.data.sort_index }, (data) => {
      //如果是下拉加载时 先将评论数组清空 
      if (page_index == 1) {
        //默认进来进来 或者刷新时调用
        that.data.storeListArr.splice(0, that.data.storeListArr.length);
        if (data.length > 0) {
          that.data.storeListArr = that.data.storeListArr.concat(data);
        }
      }
      else {
        //加载更多数据
        if (data.length > 0) {
          that.data.storeListArr = that.data.storeListArr.concat(data);
        }
      }
      that.setData({
        is_show_load_bg: false,
        store_list: that.data.storeListArr,
      });
      that.data.page_index = parseInt(that.data.page_index) + 1;
    }, that, { isShowLoading: false });
  },

  //获取定位
  getLocation: function () {
    var that = this;
    // 页面初始化 options为页面跳转所带来的参数
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var qqmapsdk = util.getMapSdk()
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            var addressD = res.result.address_component;
            var addressS = '';
            if (addressD.street_number) {
              addressS = addressD.street_number;
            }
            else if (addressD.street) {
              addressS = addressD.street;
            }
            else if (addressD.city) {
              addressS = addressD.city;
            }
            res = res.result;
            wx.setStorageSync('LATITUD', res.location.lat);
            wx.setStorageSync('LONGITUDE', res.location.lng);
            wx.setStorageSync('ADDRESS', addressS);
            that.setData({
              address: addressS,
              is_show_getLocation: false,
            });
            that.data.page_index = 1;
            that.getManyStoresSource();
          }
        });
      },
      complete: function () {
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  //设置分享
  onShareAppMessage: function () {
    var that = this
    if (that.data.store_type == 2) {
      return {
        title: that.data.g_share_title,
        desc: that.data.g_share_desc,
        path: '/pages/store/store-home/index'
      }
    }
    else {
      return {
        title: that.data.store_data.store_name,
        desc: that.data.store_data.store_jieshao,
        path: '/pages/store/store-home/index'
      }
    }

  },
  //点击广告图
  advert_top_bind: function (e) {
    var that = this;
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    });
  },

  //用户点击分类
  store_category_click: function (e) {
    // var that = this;
    // that.data.param.keyword='';
    // that.data.store_cate = e.currentTarget.id;
    // var cate_name = e.currentTarget.dataset.cate_name;
    // if (cate_name == '全部') {
    //   that.data.store_cate = '';
    // }
    // that.data.page_index = 1;
    // that.getStoreList();
    // this.setData({
    //   toView: 'store_list'
    // })

    var that = this;
    wx.navigateTo({
      url: '../store-list/index?cate_id=' + e.currentTarget.id + '&cate_name=' + e.currentTarget.dataset.cate_name
    });

  },
  onShowSearchTap: function () {
    //显示搜索框
    this.setData({ searchShow: true, });
  },
  onHideSearchBlur: function (e) {
    console.log(1111111111111111111111);
    //隐藏搜索框
    // if (!e.detail.value)
    // var a = this.data.param;
    // a.keyword = '';
    // this.setData({
    //   searchShow: false,
    //   param: a
    // });
  },
  onSearchSubmit: function (e) {
    //搜索操作
    var that = this;
    that.data.param.keyword = e.detail.value.keyword;
    that.data.store_cate = '';
    that.data.page_index = 1;
    that.getStoreList();
    this.setData({
      search_p: that.data.param.keyword,
      param: that.data.param
    })
  },
  onClearKeywordTap: function () {
    //清除关键字
    this.data.param.keyword = '';
    this.setData({ param: this.data.param });
  },
  keyboardComplete:function(e){
//搜索框完成按键事件
    var that = this;
    this.setData({ searchShow: false, });
    that.data.param.keyword = e.detail.value;
    that.data.store_cate = '';
    that.data.page_index = 1;
    that.getStoreList();
  },
  /**
 * 打开地图
 */
  onOpenMapTap: function (e) {

    var that = this;
    wx.chooseLocation({
      success: (res) => {
        that.setData({
          is_show_getLocation: false,
          address: res.name
        });
        wx.setStorageSync('LATITUD', res.latitude);
        wx.setStorageSync('LONGITUDE', res.longitude);
        wx.setStorageSync('ADDRESS', res.name);
        that.data.page_index = 1;
        that.getManyStoresSource();
      }
    });

    // wx.chooseLocation({
    //   success: (e) => {
    //     that.data.page_index = 1;
    //     qqmapsdk.reverseGeocoder({
    //       location: {
    //         latitude: e.latitude,
    //         longitude: e.longitude
    //       },
    //       success: (res) => {
    //         var addressD = res.result.address_component;
    //         var addressS = '';
    //         if (addressD.street_number) {
    //           addressS = addressD.street_number;
    //         }
    //         else if (addressD.street) {
    //           addressS = addressD.street;
    //         }
    //         else if (addressD.city) {
    //           addressS = addressD.city;
    //         }
    //         res = res.result;
    //         wx.setStorageSync('LATITUD', res.location.lat);
    //         wx.setStorageSync('LONGITUDE', res.location.lng);
    //         wx.setStorageSync('ADDRESS', addressS);
    //         that.setData({
    //           address: addressS
    //         });
    //         that.getManyStoresSource();
    //       }
    //     });
    //   }
    // });
  },
  //跳转店铺详情
  store_info_bind: function (e) {
    var that = this;
    var is_show_home_page = e.currentTarget.dataset.is_show_home_page
    var xcx_appid = e.currentTarget.dataset.xcx_appid
    //直接跳转店铺小程序
    if(xcx_appid){
      wx.navigateToMiniProgram({
        appId: xcx_appid,
        path: '',
        extraData: {
          foo: 'bar'
        },
        envVersion: 'release',
        success(res) {
          console.log(res);
        },
        fail(res){
          console.log(res);
        }
      })
    }
   else if (is_show_home_page==1){
      wx.navigateTo({
        url: '../store-info/index?store_id=' + e.currentTarget.id
      });
    }
    else
    {
      wx.navigateTo({
        url: '../store-goods-list/index?store_id=' + e.currentTarget.id
      });
    }
  
  },
  ruzhu_bind: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../store-ruzhu/index'
    });
  },
  //------------------------------ 多门店首页end-------------------------------------

  //-------------------------------单门店首页start-----------------------------------
  //快速买单
  rapid_pay_bind: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../store-rapid-pay/index?store_id=' + that.data.this_store_id
    });
  },
  //跳转优惠券列表
  coupon_list_bind: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../store-coupon/index?list_type=1&store_id=' + that.data.this_store_id
    });
  },
  //跳转商品详情
  goods_info_bind: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../store-goods-details/index?goods_id=' + e.currentTarget.id + '&store_id=' + that.data.this_store_id
    });
  },
  //跳转商品列表
  goods_list_bind: function (e) {
    var that = this;
    var consume_type = e.currentTarget.dataset.consume_type;
    wx.navigateTo({
      url: '../store-goods-list/index?consume_type=' + consume_type + '&store_id=' + that.data.this_store_id
    });
  },
  //活动公告
  huodong_info_bind: function () {
    var that = this;
    wx.navigateTo({
      url: '../store-active/index?&store_id=' + that.data.this_store_id
    });
  },
  //领券页面
  huodong_quan_info_bind: function () {
    var that = this;
    wx.navigateTo({
      url: '../store-juan/index?&store_id=' + that.data.this_store_id
    });
  },
  //订单
  go_user_order_bind: function (e) {
    wx.navigateTo({
      url: '/pages/store/store-order-list/index'
    });
  },
  //导航
  get_location_bind: function () {
    var that = this;
    var loc_lat = that.data.store_data.store_gps_lat;
    var loc_lng = that.data.store_data.store_gps_lng;
    wx.openLocation({
      latitude: parseFloat(loc_lat),
      longitude: parseFloat(loc_lng),
      scale: 18,
      name: that.data.store_data.store_name,
      address: that.data.store_data.store_address
    });
  },
  //电话
  call_phone_bind: function () {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.store_data.store_con_mobile
    });
  },
  //获取店铺信息 包含店铺商品
  getStoreInfo: function () {
    var that = this;
    requestUtil.get(_DgData.duoguan_host_api_url + '/index.php?s=/addon/DgStore/StoreApi/getStoreHomeInfo.html', { store_id: that.data.this_store_id, versions: 2 }, (info) => {
      var store_data = info;
      that.data.store_data = store_data;
      that.setData({
        is_show_load_bg: false,
        store_data: store_data,
        comment_data: store_data.recommend_comments,
        comment_title: '最新评价'
      });


      var handler = {
        setData: (bindData) => {
          _.each(bindData.content.images, (item, index) => {
            if (item.attr.src.indexOf('http') !== 0) {
              item.attr.src = _data.DUOGUAN_HOST_URL + item.attr.src;
              bindData.content.imageUrls[index] = item.attr.src;
            }
          });
          this.setData(bindData);
        }
      };
      WxParse.wxParse('content', 'html', info.store_intro, handler);
      this.wxParseImgLoad = handler.wxParseImgLoad;
      this.wxParseImgTap = handler.wxParseImgTap;

      wx.setNavigationBarTitle({
        title: store_data.store_name
      });

    },that,{ isShowLoading: false });
  },

  //立即购买
  buy_now: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../store-order-sure/index?store_id=' + that.data.this_store_id + '&consume_type=1&goods_id=' + e.currentTarget.id
    });
  },

  //-------------------------------单门店首页end-----------------------------------
})